package org.example.maibobo.decode;

import org.example.maibobo.encode.CurrentMeasurementDataEncodeResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartboot.socket.transport.AioSession;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import static org.example.util.ProcessorUtil.byteArrayToHexString;
import static org.example.util.ProcessorUtil.calculateChecksum;

public class CurrentMeasurementDataDecode implements Decode {

    private static final Logger LOGGER = LoggerFactory.getLogger(CurrentMeasurementDataDecode.class);

    /**
     * 当次测量结果
     *
     * @param session
     * @param data
     */
    @Override
    public void decoder(AioSession session, byte[] data) throws IOException {
        ByteBuffer buffer = ByteBuffer.wrap(data);
        buffer.order(ByteOrder.BIG_ENDIAN);

        // 验证前导码
        // 解析前导码
        int leadingCode1 = buffer.get() & 0xFF;
        int leadingCode2 = buffer.get() & 0xFF;
        LOGGER.debug("前导码1: 0x" + Integer.toHexString(leadingCode1));
        LOGGER.debug("前导码2: 0x" + Integer.toHexString(leadingCode2));

        // 传输方式
        byte transportMode = buffer.get();
        LOGGER.debug("传输方式: " + transportMode);

        // 协议版本号
        byte protocolVersion = buffer.get();
        LOGGER.debug("协议版本号: " + protocolVersion);

        // 软件版本号
        byte softwareVersion = buffer.get();
        LOGGER.debug("软件版本号: " + softwareVersion);

        // 长度
        short length = buffer.getShort();
        LOGGER.debug("长度(2byte): " + length);

        // 数据类型
        byte dataType = buffer.get();
        LOGGER.debug("数据类型: " + dataType);

        // 设备公司编码
        byte deviceCompanyCode = buffer.get();
        LOGGER.debug("设备公司编码: " + deviceCompanyCode);

        // 设备类型
        byte deviceType = buffer.get();
        LOGGER.debug("设备类型: " + deviceType);

        // 设备型号
        byte deviceModel = buffer.get();
        switch (deviceModel) {
            case 0x6B:
                LOGGER.debug("Device model: RBP-9801");
                break;
            case 0x20:
                LOGGER.debug("Device model: RBP-200");
                break;
            default:
                LOGGER.debug("Device model: Unknown");
                break;
        }

        // 设备编码
        byte[] deviceCode = new byte[7];
        buffer.get(deviceCode);
        String deviceCodeStr = byteArrayToHexString(deviceCode);
        LOGGER.debug("设备编码: " + deviceCodeStr);

        // SIM卡号码
        byte[] simNumber = new byte[7];
        buffer.get(simNumber);
        String simNumberStr = byteArrayToHexString(simNumber);
        LOGGER.debug("SIM卡号码: " + simNumberStr);


        // 用户编号
        byte userCode = buffer.get();
        switch (deviceModel) {
            case 0x00:
                LOGGER.debug("单用户设备: " + userCode);
                break;
            case 0x01:
                LOGGER.debug("用户1的测量结果: " + userCode);
                break;
            case 0x02:
                LOGGER.debug("用户2的测量结果: " + userCode);
                break;
            default:
                LOGGER.debug("未知区域: " + userCode);
                break;
        }

        // 时间戳
        byte[] timestamp = new byte[5];
        buffer.get(timestamp);
        String timestampStr = byteArrayToHexString(timestamp);
        LOGGER.debug("时间戳: " + timestampStr);

        byte[] measuredData = new byte[5];
        buffer.get(measuredData);
        String measuredData_str = byteArrayToHexString(measuredData);
        LOGGER.debug("测量数据(5byte): " + measuredData_str);

        LOGGER.debug("收缩压:" + (measuredData[1] & 0xff) + "mmHg");
        LOGGER.debug("舒张压:" + (measuredData[3] & 0xff) + "mmHg");
        LOGGER.debug("脉搏数:" + (measuredData[4] & 0xff) + "次/分钟");

        // 校验位
        byte checksum = buffer.get();
        LOGGER.debug("校验位: " + checksum);

        System.out.println();

        // 验证校验结果
        byte calculatedChecksum = calculateChecksum(data, 2, data.length - 1);
        boolean isValid = checksum == calculatedChecksum;
        LOGGER.debug("校验结果: " + (isValid ? "通过" : "失败"));
        //校验通过
        if (isValid) {
            //普通协议发送
            session.writeBuffer().write(CurrentMeasurementDataEncodeResponse.encodeProtocol());
        }
    }
}
